/*
* Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
* Description: yuv数据发送
*/

#ifndef IMAGE_SENDER_YUV_SENDER_H_
#define IMAGE_SENDER_YUV_SENDER_H_

#include "stdio.h"
#include "stdlib.h"
#include "image_sender_base.h"
#include "util.h"
#include "mdc/cam/camera/cameradecodedmbufserviceinterface_skeleton.h"
using namespace std;
using namespace cv;

using Skeleton = mdc::cam::camera::skeleton::CameraDecodedMbufServiceInterfaceSkeleton;
class YuvSender : public ImageSenderBase<Skeleton>
{
public:
    YuvSender() = default;
    YuvSender(uint32_t id, cv::Size s, std::string dir): ImageSenderBase<Skeleton>(id, s, dir)
    {
        sourceYuvPath = dir;
        if (dir.back() != '/') {
            sourceYuvPath += string("/") += "yuvSource.yuv";
        } else {
            sourceYuvPath += "yuvSource.yuv";
        }
#ifdef SAVE_SENDER_FILE
        fpYuv = fopen(sourceYuvPath.c_str(), "wb+");
#endif
        sec = chrono::high_resolution_clock::now();
    }
    ~YuvSender() = default;
    bool RegisterSender()
    {
        std::cout << "Begin register normal image sender." << endl;
        auto result = ImageSenderBase<Skeleton>::RegisterSender();
        std::cout << "Finished to register normal image sender." << endl;
        return result;
    }

    void FillImageAndSend(std::string yuvPath, uint32_t seq, void *flag) override
    {
        (void)flag;
        std::string path = dir;
        std::string postfix = comPara.fileType;
        bool isLoop = comPara.loop;
        cout << "dir : " << dir << "\t" << "postfix :" << postfix << endl;
        std::vector<std::string> files;
        int32_t fileCnt = GetFilesBySort(path, files, comPara.fileType);
        if (fileCnt == 0) {
            cout << "PATH:" << path << " has no files!" << endl;
            return;
        }
        do {
            for (auto &file : files) {
                int32_t w = imgSize.width;
                int32_t h = imgSize.height;
                FILE *yuvFile;
                yuvFile = fopen(file.c_str(), "rb");
                if (yuvFile == nullptr) {
                    cout << "Open yuv file failed!" << endl;
                    return;
                }
                int32_t frameSize = w * h * 3 / 2;
                fseek(yuvFile, 0, SEEK_END);
                int32_t fileSize = ftell(yuvFile);
                rewind(yuvFile);
                int32_t frameCount = fileSize / frameSize;
                char *yuvBuff = (char *)malloc(frameSize * sizeof(char));
                if (nullptr == yuvBuff) {
                    std::cout << "malloc yuvBuff memory error" << std::endl;
                    return;
                }
                for (int32_t i = 0; i < frameCount; i++) {
                    Mat yUV420NV12;
                    yUV420NV12.create(h * 1.5, w, CV_8UC1);
                    memset(yuvBuff, 0, frameSize);
                    fread(yuvBuff, sizeof(char), frameSize, yuvFile);
                    memcpy(yUV420NV12.data, yuvBuff, frameSize);
                    auto imagePub = dataSkeleton->cameraDecodedMbufEvent.Allocate();
                    imagePub->CameraHeader.FrameId = frameID;
                    imagePub->CameraHeader.Seq = seq;
                    imagePub->Width = w;
                    imagePub->Height = h;
                    imagePub->DataSize = frameSize;
                    imagePub->UdpData.assign(yUV420NV12.data, yUV420NV12.data + imagePub->DataSize);
#ifdef SAVE_SENDER_FILE
                    fwrite(yUV420NV12.data, 1, frameSize, fpYuv);
#endif
                    if (comPara.time.empty()) {
                        timeval now;
                        gettimeofday(&now, NULL);
                        imagePub->CameraHeader.Stamp.Sec = now.tv_sec;
                        imagePub->CameraHeader.Stamp.Nsec = now.tv_usec * 1000U;
                    } else {
                        time_t timeStamp = ConvertTimeStr2TimeStamp(comPara.time);
                        auto t1 = chrono::high_resolution_clock::now();
                        int64_t duration = (t1 - sec).count() / 1000000000.0;
                        imagePub->CameraHeader.Stamp.Sec = timeStamp + duration;
                        printf("timeStamp=%ld\n", timeStamp + duration);
                    }
                    dataSkeleton->cameraDecodedMbufEvent.Send(move(imagePub));
                    cout << "Begin send yuv. seq:" << seq << " frameID:" << frameID << " path:" << file << endl;
                    if (comPara.frequency != "") {
                        int32_t freq = atoi(comPara.frequency.c_str());
                        // 1000000微秒
                        int32_t sleepTime = 1000000 / freq;
                        usleep(sleepTime);
                    } else {
                        // 30hz 100000微秒
                        usleep(1000000 / 30);
                    }
                }
                free(yuvBuff);
            }
        } while (isLoop);
#ifdef SAVE_SENDER_FILE
        fclose(fpYuv);
#endif
    }
private:
    std::string sourceYuvPath { };
    FILE *fpYuv { nullptr };
    chrono::high_resolution_clock::time_point  sec { };//-t used
};

#endif //IMAGE_SENDER_YUV_SENDER_H_
